package com.starsea.book.ui.newpage

import android.animation.ValueAnimator
import android.app.AlertDialog
import android.content.DialogInterface
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Bundle
import android.text.Html
import android.widget.ImageView
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ImageUtils
import com.blankj.utilcode.util.LogUtils
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.TTAdConstant
import com.bytedance.sdk.openadsdk.TTAdLoadType
import com.bytedance.sdk.openadsdk.TTAdNative
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.bytedance.sdk.openadsdk.TTRewardVideoAd
import com.starsea.book.R
import com.starsea.book.base.VMBaseActivity
import com.starsea.book.databinding.ActivityLotteryPanBinding
import com.starsea.book.ui.newpage.adapter.LotteryRecordAdapter
import com.starsea.book.ui.newpage.entity.LotteryInfoEntity
import com.starsea.book.ui.newpage.utils.finialDouble
import com.starsea.book.ui.newpage.viewmodel.WelfareViewModel
import com.starsea.book.ui.newpage.weidget.welfaregame.RotateListener
import com.starsea.book.ui.newpage.weidget.welfaregame.WheelSurfView
import com.starsea.book.utils.toastOnUi
import com.starsea.book.utils.viewbindingdelegate.viewBinding


/**
 * @author Lee
 * @createTime 2024-02-22 14 GMT+8
 * @desc : 转盘抽奖
 */
class LotteryPanActivity : VMBaseActivity<ActivityLotteryPanBinding, WelfareViewModel>() {

    override val binding by viewBinding(ActivityLotteryPanBinding::inflate)
    override val viewModel by viewModels<WelfareViewModel>()

    lateinit var mAdapter: LotteryRecordAdapter

    var listLottery: List<LotteryInfoEntity> = arrayListOf()

    var allCount = 0

    override fun onActivityCreated(savedInstanceState: Bundle?) {


        viewModel.lotteryList(1)
        viewModel.lotteryRedordReward(1)
        viewModel.lotteryNumberCheck(1, true)

        mAdapter = LotteryRecordAdapter(this, 1) {

        }

        binding.rvRecord.layoutManager = LinearLayoutManager(this)
        binding.rvRecord.adapter = mAdapter


        viewModel.lotteryNumberCheckResult.observe(this) {
            if (it.status == 200) {

                binding.rtvNumber.text = "今日剩余抽奖次数：${it.data!!.allCount}"


                binding.tvRule.text = Html.fromHtml(it.data!!.drawsRule ?: "")
                allCount = it.data!!.allCount ?: 0

                if (!it.data!!.isCheck) {
                    if ((it.data!!.allCount ?: 0) > 0) {
                        ////下次抽奖是否要看视频 (0:否; 1:是)
                        if (it.data!!.nextIsAdvert == 1) {
                            val builder: AlertDialog.Builder =
                                AlertDialog.Builder(this@LotteryPanActivity)
                            builder.setTitle("温馨提示")
                            builder.setMessage("是否观看视频抽奖？")
                            builder.setPositiveButton("确定",
                                DialogInterface.OnClickListener { dialog, which -> //模拟位置
//                                    val position: Int = Random.nextInt(6) + 1
//                                    binding.lotteryView.startRotate(position)
                                    //看视频广告
//                                    viewModel.adverReward("", 4)

                                    showAdaVideo(4)
                                })
                            builder.setNegativeButton(
                                "取消"
                            ) { dialog, which ->

                            }
                            builder.show()
                        } else {
                            viewModel.lotteryPan()
                            binding.rtvNumber.text =
                                "今日剩余抽奖次数：${(it.data!!.allCount ?: 0) - 1}"
                        }
                    } else {
                        toastOnUi("今日抽奖次数已用完")
                    }
                }

            } else if (it.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(this)
            } else {
                toastOnUi(it.msg)
            }
        }


        viewModel.advertResult.observe(this) { data ->
            if (data.status == 200) {
                viewModel.lotteryPan()
                binding.rtvNumber.text =
                    "今日剩余抽奖次数：${allCount - 1}"
            } else if (data.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(this)
            } else {
                toastOnUi(data.msg)
            }
        }

        viewModel.lotteryRecordResult.observe(this) { data ->
            if (data.status == 200) {
                mAdapter.setItems(data.data!!)
            } else if (data.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(this)
            } else {
                toastOnUi(data.msg)
            }
        }


        viewModel.lotteryPanResult.observe(this) { data ->
            if (data.status == 200) {
                //                                    val position: Int = Random.nextInt(6) + 1
//                                    binding.lotteryView.startRotate(position)
                val position =
                    listLottery.indexOfFirst { it.drawPrizeId == data.data!!.drawPrizeId }
                binding.lotteryView.startRotate(position)

            } else if (data.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(this)
            } else {
                toastOnUi(data.msg)
            }
        }


        viewModel.lotteryResult.observe(this) {
            if (it.status == 200) {

                var imgs: MutableList<Bitmap> =
                    arrayListOf()
                val mColors: MutableList<Int> =
                    arrayListOf()
//                val mColors =
//                    arrayOf(
//                        Color.parseColor("#FEE7A1"),
//                        Color.parseColor("#ffffff"),
//                        Color.parseColor("#FEE7A1"),
//                        Color.parseColor("#ffffff"),
//                        Color.parseColor("#FEE7A1"),
//                        Color.parseColor("#ffffff")
//                    )

                it.data!!.forEachIndexed { index, lotteryInfoEntity ->
                    lotteryInfoEntity.descString = if (lotteryInfoEntity.amountType == 1) {
                        "${(lotteryInfoEntity.amount ?: "0").toDouble().finialDouble()}金币"
                    } else {
                        "${(lotteryInfoEntity.amount ?: "0").toDouble().finialDouble()}天"
                    }

                    if (lotteryInfoEntity.amountType == 1) {
                        imgs.add(ImageUtils.getBitmap(R.mipmap.icon_welfare_lottery_coin))
                    } else {
                        imgs.add(ImageUtils.getBitmap(R.mipmap.icon_welfare_lottery_vip))
                    }

                    if (index % 2 == 0) {
                        mColors.add(Color.parseColor("#FEE7A1"))
                    } else {
                        mColors.add(Color.parseColor("#ffffff"))
                    }
                }

                listLottery = it.data!!
                imgs = WheelSurfView.rotateBitmaps(imgs) as ArrayList<Bitmap>

                binding.lotteryView.setConfig(
                    WheelSurfView.Builder()
                        .setmDeses(it.data!!)
                        .setmIcons(imgs)
                        .setmColors(mColors)
                        .setmTextColor(Color.parseColor("#FF210D"))
                        .setmTypeNum(imgs.size)
                        .setmGoImgRes(R.mipmap.icon_lottery_go_img)
                        .setmHuanImgRes(R.mipmap.lottery_huan)
                        .build()
                )
            } else if (it.status == 401) {
                toastOnUi("登录过期,请重新登录")
                LoginActivity.start(this)
            } else {
                toastOnUi(it.msg)
            }
        }





        binding.lotteryView.setRotateListener(object : RotateListener {
            override fun rotateEnd(position: Int, des: String?) {
            }

            override fun rotating(valueAnimator: ValueAnimator?) {
            }

            override fun rotateBefore(goImg: ImageView?) {
//                val builder: AlertDialog.Builder = AlertDialog.Builder(this@LotteryPanActivity)
//                builder.setTitle("温馨提示")
//                builder.setMessage("确定要花费100积分抽奖？")
//                builder.setPositiveButton("确定",
//                    DialogInterface.OnClickListener { dialog, which -> //模拟位置
//                        val position: Int = Random.nextInt(6) + 1
//                        binding.lotteryView.startRotate(position)
//                    })
//                builder.setNegativeButton("取消",
//                    DialogInterface.OnClickListener { dialog, which -> })
//                builder.show()

                viewModel.lotteryNumberCheck(1, false)

            }

        })


    }

    private fun showAdaVideo(type: Int) {
        showLoading("广告加载中...")
        //创建TTAdNative对象，createAdNative(Context context) context需要传入Activity对象
        val mTTAdNative =
            TTAdSdk.getAdManager().createAdNative(this)

        val adSlot = AdSlot.Builder()
            .setCodeId("956204408")
            .setOrientation(TTAdConstant.VERTICAL)
            .setAdLoadType(TTAdLoadType.LOAD)
            .build()

        mTTAdNative.loadRewardVideoAd(adSlot,
            object : TTAdNative.RewardVideoAdListener {
                override fun onError(p0: Int, p1: String?) {
                    LogUtils.e(">>>> p0 = ${p0} \n p1 = ${p1}")
                }

                override fun onRewardVideoAdLoad(p0: TTRewardVideoAd?) {
                }

                override fun onRewardVideoCached() {
                }

                override fun onRewardVideoCached(ttRewardVideoAd: TTRewardVideoAd?) {
                    dismissLoading()
                    ttRewardVideoAd!!.showRewardVideoAd(this@LotteryPanActivity)

                    ttRewardVideoAd.setRewardAdInteractionListener(object :
                        TTRewardVideoAd.RewardAdInteractionListener {
                        override fun onAdShow() {
                            LogUtils.e(">>>> 广告展示")
                            // 广告展示
                        }

                        override fun onAdVideoBarClick() {
                            // 广告点击
                            LogUtils.e(">>>> 广告点击")
                        }

                        override fun onAdClose() {
                            // 广告关闭
                            LogUtils.e(">>>> 广告关闭")
                        }

                        override fun onVideoComplete() {
                            LogUtils.e(">>>> 广告素材播放完成，例如视频未跳过，完整的播放了")
                        }

                        override fun onVideoError() {
                            LogUtils.e(">>>> 广告展示时出错")
                        }

                        override fun onRewardVerify(
                            p0: Boolean,
                            p1: Int,
                            p2: String?,
                            p3: Int,
                            p4: String?
                        ) {
                        }

                        // 奖励发放
                        override fun onRewardArrived(
                            p0: Boolean,
                            p1: Int,
                            p2: Bundle?
                        ) {
                            toastOnUi("奖励已发放")

                            viewModel.adverReward("", type)

                            LogUtils.e(">>>> 奖励发放")
                            LogUtils.e(">>>> p0 = ${p0} \n p1 = ${p1} \n ")
                        }

                        // // 用户在观看时点击了跳过
                        override fun onSkippedVideo() {
                            LogUtils.e(">>>> 用户在观看时点击了跳过")
                        }

                    })
                }
            })


    }
}